﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MDReader.Control
{
    public partial class CtrlOutline : UserControl
    {
        public CtrlOutline()
        {
            InitializeComponent();
            Root = new TreeNode("大纲");
        }

        public event EventHandler<OutlineItemSelectedEventArgs>? OutlineItemSelected;
        private TreeNode Root;
        public void LoadOutline_Obsolated(List<OutlineItem> outlineItems)
        {
            Root.Nodes.Clear();
            foreach (var item in outlineItems)
            {
                var node = new TreeNode(item.Text) { Tag = item };
                Root.Nodes.Add(node);
            }
            treeView.ExpandAll();
        }
        public void LoadOutline(List<OutlineItem> outlineItems)
        {
            Root.Nodes.Clear();
            TreeNode? currentNode = Root;
            Stack<TreeNode> nodeStack = new Stack<TreeNode>();
            nodeStack.Push(Root);

            foreach (var item in outlineItems)
            {
                var node = new TreeNode(item.Text) { Tag = item };

                while (nodeStack.Count > 1 && ((OutlineItem)nodeStack.Peek().Tag).Level >= item.Level)
                {
                    nodeStack.Pop();
                }

                currentNode = nodeStack.Peek();
                currentNode.Nodes.Add(node);
                nodeStack.Push(node);
            }

            treeView.ExpandAll();
        }
        private void TreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            OutlineItem? item = e?.Node?.Tag as OutlineItem;
            if (item != null && OutlineItemSelected != null)
                OutlineItemSelected?.Invoke(this, new OutlineItemSelectedEventArgs { Item = item });
        }

        private void CtrlOutline_Load(object sender, EventArgs e)
        {
            treeView.Nodes.Clear();
            treeView.Nodes.Add(Root);
        }

        public void ClearContent()
        {
            Root?.Nodes?.Clear();
        }

    }
    public class OutlineItem
    {
        public int Level { get; set; }
        public string Text { get; set; } = "";
        public string Id { get; set; } = "";
        public int LineNumber { get; set; }
    }
    public class OutlineItemSelectedEventArgs : EventArgs
    {
        public OutlineItem Item { get; set; } = new OutlineItem();
    }
}
